// 被代理接口
public interface Service {
    void doSomething();
}

// 实际业务逻辑实现(被代理对象)
public class RealService implements Service{
    @Override
    public void doSomething(){
        System.out.println("Doing something...");
    }
}
    
// 代理类实现了相同的接口
public class StaticProxy implements Service {

    private final Service realService;

    public StaticProxy(Service realService){
        this.realService = realService;
    }

    @Override
    public void doSomething() {
        // 执行之前的操作
        System.out.println("Before doing something...");

        // 调用实际业务逻辑
        realService.doSomething();

        // 执行之后的操作
        System.out.println("After doing something...");
    }
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyDemo {

    public static void main(String[] args) {
        
        // 创建真实主题实例
        Service serviceImpl = new RealService();

        // 创建动态代理处理器
        InvocationHandler handler = (proxy, method, arguments) -> {
            System.out.println("before");
            Object result = method.invoke(serviceImpl, arguments);
            System.out.println("after");
            return result;
        };

        // 获取到动态代理的对象 
        Service proxyInstance = (Service) Proxy.newProxyInstance(
                serviceImpl.getClass().getClassLoader(),
                new Class<?>[]{Service.class},
                handler);

        // 使用代理调用方法
        proxyInstance.doSomething(); 
    }
}
